package com.example.demo.service.impl;

import com.example.demo.pojo.ModelInfo;
import com.example.demo.service.IModelService;
import com.example.demo.state.BaseConstants;
import com.example.demo.util.PageInfo;
import com.example.demo.util.PageUtil;
import com.example.demo.util.ResultData;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Model;
import org.activiti.engine.repository.ModelQuery;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;

@Service
public class ModelServiceImpl implements IModelService {

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private ObjectMapper objectMapper;



    @Override
    public ResultData pageByIdNameKeyModel(ModelInfo modelInfo, Integer pageNum, Integer pageSize) {
        ModelQuery modelQuery = repositoryService.createModelQuery();
        if(modelInfo != null){
            //id不为空
            if (StringUtils.isNotBlank(modelInfo.getId())) {
                //设置id为查询条件
                modelQuery.modelId(modelInfo.getId());
            }
            //Key不为空
            if(StringUtils.isNotBlank(modelInfo.getKey())) {
                //设置key为查询条件
                modelQuery.modelKey(modelInfo.getKey());
            }
            //Name不为空
            if(StringUtils.isNotBlank(modelInfo.getName())){
                //设置name为查询条件
                modelQuery.modelNameLike("%" + modelInfo.getName() + "%");
            }
        }
        //以创建时间降序排序
        modelQuery.orderByCreateTime().desc();
        //统计总条数
        Long total = modelQuery.count();
        //分页查询
        List<Model> models = modelQuery.listPage(pageNum - 1, pageSize);
        PageInfo<Model> pageModels = PageUtil.toPageInfo(models);
        if(total != null) {
            pageModels.setTotal(total);
        }
        return ResultData.createBySuccess("模型查询成功！",pageModels);
    }

    @Override
    public ResultData saveModel(String modelId, String name, String description, String json_xml, String svg_xml) {
        try {

            Model model = repositoryService.getModel(modelId);

            //此处如果之前画好后，又被删除流程，保存时出现空指针异常
            if(model == null){
                return ResultData.createByErrorMessage("模型异常");
            }
            ObjectNode modelJson = (ObjectNode) objectMapper.readTree(model.getMetaInfo());
            //设置名称
            modelJson.put(BaseConstants.MODEL_NAME, name);
            //设置描述
            modelJson.put(BaseConstants.MODEL_DESCRIPTION, description);
            model.setMetaInfo(modelJson.toString());
            model.setName(name);
            model.setVersion(model.getVersion() + 1);
            repositoryService.saveModel(model);
            //todo 此处也需要判断json_xml和svg_xml是否存在，
            repositoryService.addModelEditorSource(model.getId(), Objects.requireNonNull(json_xml.getBytes(StandardCharsets.UTF_8)));

            InputStream svgStream = new ByteArrayInputStream(Objects.requireNonNull(svg_xml.getBytes(StandardCharsets.UTF_8)));
            TranscoderInput input = new TranscoderInput(svgStream);

            PNGTranscoder transcoder = new PNGTranscoder();
            // Setup output
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            TranscoderOutput output = new TranscoderOutput(outStream);

            // Do the transformation
            transcoder.transcode(input, output);
            final byte[] result = outStream.toByteArray();
            repositoryService.addModelEditorSourceExtra(model.getId(), result);
            outStream.close();
            return ResultData.createByErrorMessage("保存成功");

        } catch (Exception e) {

            throw new ActivitiException("Error saving model", e);
        }
    }


}
